export type Middleware<T> = (ctx: T, next: () => Promise<void>) => Promise<void>;
export type MiddlerCode<T> = (ctx: T) => Promise<void>;

export class Middler<T> {
  list: Middleware<T>[] = [];
  constructor(list: Middleware<T>[]) {
    this.list = list;
  }
  use(...args: Middleware<T>[]) {
    this.list.push(...args);
  }
  exec(ctx: any, core: MiddlerCode<T>) {
    let count = 0;
    const next = () => {
      if (count < this.list.length) {
        return this.list[count++](ctx, next);
      } else {
        return core(ctx);
      }
    };
    return next();
  }
}
